<template>
    <div class='diction'>
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item>
                <el-button type="primary" plain icon="el-icon-plus" size="mini"  @click="handleAdd" v-hasPermi="['system:menu:add']" >新增</el-button>
            </el-form-item>
        </el-form>
        <el-tabs type="border-card" v-model="active" @tab-click="settabnav">
            <el-tab-pane name='1' label="一级服务" />
            <el-tab-pane name='2' label="二级服务" />
            <tabelItem :list='list' :type='active' @openEditItem='openEditItem' @delItem='delItem'></tabelItem>
        </el-tabs>
        <div style="text-align:right;margin-top:20px;" v-if='queryParams.total>0'>
            <el-pagination background layout="prev, pager, next" @current-change="handleQuery" :current-page.sync="queryParams.pageNum" :page-size="queryParams.pageSize" :total="queryParams.total"> </el-pagination>
        </div>
        <mydialog :dialogTitle='dialogTitle' @handleClose='setShowDialog' @serve='serve' :showwidth="'600px'" :show='showDialog'>
            <template slot="cont" class="mycont">
                <el-form v-model="form" label-width="100px">
                    <el-form-item v-if='type==2' label="一级服务名称">
                        <el-select v-model="onename" filterable placeholder="请选择">
                            <el-option v-for="item in oneArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="服务名称">
                        <el-input v-model="form.serviceName" maxlength='50'></el-input>
                    </el-form-item>
                    <el-form-item label="服务描述">
                        <el-input v-model="form.serviceDesc" maxlength="200"></el-input>
                    </el-form-item>
                    <p v-if='type==2'>添加服务功能：</p>
                    <el-form-item v-if='type==2' label="完成时间">
                        <div class="form_item">
                            <span>是否开启</span>
                            <el-switch class="form_item_switch" v-model="showitemr" active-text="是" inactive-text="否" active-color="#1890ff" inactive-color="#999"></el-switch>
                            <el-select v-if='showitemr' class="form_item_select" style="width:180px;" v-model="addItem" placeholder="请添加完成时间">
                                <el-option style="width:180px;" v-for="item in addItemr" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                            <el-button @click='addRepeatDesc(1)' class="form_item_btn" size="small" v-if="showitemr" type="primary">添加选项</el-button>
                        </div>
                    </el-form-item>
                    <el-form-item v-if='type==2' label="查重率">
                        <div class="form_item">
                            <span>是否开启</span>
                            <el-switch class="form_item_switch" v-model="showrepea" active-text="是" inactive-text="否" active-color="#1890ff" inactive-color="#999"></el-switch>
                            <el-select class="form_item_select" v-if="showrepea" style="width:180px;" v-model="addRepea" placeholder="请添加查重率">
                                <el-option style="width:180px;" v-for="item in addRepeat" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                            <el-button @click='addRepeatDesc(2)' class="form_item_btn" size="small" v-if="showrepea" type="primary">添加选项</el-button>
                        </div>
                    </el-form-item>
                    <el-form-item v-if='type==1' label="服务图标">
                        <el-upload
                            :headers="headers"
                            :action="uploadUrl"
                            :before-upload="handleBeforeUpload"
                            :on-success="handleUploadSuccess"
                            :on-error="handleUploadError"
                            name="file"
                            :file-list="fileList"
                            :show-file-list='false'
                            :before-remove='removeItem'
                            ref="upload" >
                            <img v-if="imageUrl" :src="fileList[0].url" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            <!-- <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                        </el-upload>
                    </el-form-item>
                </el-form>
            </template>
        </mydialog>
    </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import tabelItem from "./tabelItem.vue";
import {selectSubjectInfos,addSubjectInfo,serviceUpdateState,addService,selectServices,deleteAttachment,serviceDelState} from '@/api/pc.js'
// import {batchUpload} from '@/api/admin.js'
export default {
    name:'diction',
    data(){
       return{
        addItemr:[],
        addItem:'',//完成时间
        addRepea:'',//查重率
        showitemr:true,//展示搜索条件
        showrepea:true,//展示搜索条件
        repeat:'',//查重率
        addRepeat:[],
        uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
        headers: {
            Authorization: "Bearer " + getToken()
        },
        active:'1',
        // 表格搜索条件
        queryParams:{
            name:'',
            status:'',
            one:'',
            tow:'',
            pageNum:1,pageSize:10,total:0
        },//期刊搜索条件
        showSearch:true,//展示搜索条件
        showDialog:false,//展示搜索条件
        list:[], //初始数据
        dialogTitle:'添加分类',//弹窗标题
        oneArr:[],//一级分类
        towArr:[],//二级分类
        form:{
            serviceName:'', //服务名称
            serviceDesc:'', //服务内容
            itemr:false,//完成时间
            repeat:false,//去重
        },
        type:1,//判断是几级分类
        imageUrl:'',//上传一级分类的图片
        onename:'',//一级分类的选中值
        towname:'',//二级分类的选中值
        fileList:[],//上传的数组
       }
    },
    components:{tabelItem},
    created(){
        this.getdata();
    },
    methods:{
        //获取当前数组
        getdata(){
            var formData = new FormData();
            formData.append('serviceType',this.type)
            formData.append('pageNum',this.queryParams.pageNum)
            formData.append('pageSize',this.queryParams.pageSize)
            selectServices(formData).then(res=>{
                this.list = res.rows;
                this.queryParams.total = res.total || 0;
            })
        },
        //搜索
        handleQuery(){
            this.getdata();
        },
        //新增
        async handleAdd(){
            this.dialogTitle = '添加服务';
            this.form.serviceName = "";
            this.form.serviceDesc = "";
            this.showitemr = false;
            this.showrepea = false;
            this.onename = "";
            this.imageUrl = '';
            this.addItemr = [];
            this.addRepeat = [];
            this.addItem = "";
            this.addRepea = "";
            if(this.active!=1){
                var formData = new FormData();
                formData.append('serviceType',1) // 固定为一级分类
                formData.append('pageNum',1)  // 固定为不分页展示所有
                formData.append('pageSize',100000)
                let res = await selectServices(formData);
                this.oneArr = res.rows&&res.rows.length>0&&res.rows.map(it=>{return {label:it.serviceName,value:it.serviceId}});
            }
            this.showDialog=true;
        },
        //点击新增
        addRepeatDesc(val){
            //查重率
            if(val==1){
                this.$prompt('请输入完成时间选项名称', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if(action === 'confirm'){
                            this.addItemr.push({label:instance.inputValue,value:this.addItemr.length+1});
                            done(false);
                        }else{
                            done();
                        } 
                    }
                });
            }else{
                this.$prompt('请输入查重率选项名称', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if(action === 'confirm'){
                            this.addRepeat.push({label:instance.inputValue,value:this.addRepeat.length+1});
                            done(false);
                        }else{
                            done();
                        } 
                    }
                });
            }
        },
        //切换选项卡
        settabnav(val){
            this.type = val.name;
            if(this.type==1){
               
            }
            this.getdata();
        },
        openEditItem(type,val){
            this.getarr(1).then(res=>{
                this.oneArr = res.rows.map(it=>{return {label:it.serviceName,value:it.serviceId}});
            });
            this.dialogTitle = '编辑服务';
            this.onename = val.parentId;
            this.form = JSON.parse(JSON.stringify(val));
            this.imageUrl = '';
            this.fileList = [];
            if(this.type==1){
                this.imageUrl = this.form.path;
                this.fileList = this.form.path?[{name:'23',url:this.form.path}]:[]
            }
            if(this.type==2){
                let obj = JSON.parse(val.serviceInfo);
                this.showitemr = obj.finishTime.flag;
                this.addItemr = typeof(obj.finishTime.list)=='string'?JSON.parse(obj.finishTime.list):[];
                this.showrepea = obj.repeatNum.flag;
                this.addRepeat = typeof(obj.repeatNum.list)=='string'?JSON.parse(obj.repeatNum.list):[];
                this.addItem = "";
                this.addRepea = "";
            }
            this.showDialog=true;
        },
        //编辑服务
        editItem(type,val){
            console.log(type)
            console.log(val)
            this.dialogTitle = '编辑服务';
            this.form.serviceId = val.serviceId;
            serviceUpdateState({serviceId:val.serviceId}).then(res=>{
                console.log(res)
                    this.form.serviceName = res.data.serviceName;
                if(type==1){
                }else if(type==2){
                    this.onename = res.data.parentId;
                }else{
                    var formData = new FormData();
                    formData.append('serviceId',res.data.firstSubjectId)
                    selectSubjectInfos(formData).then(res=>{
                        this.towArr = res.rows.map(it=>{return {label:it.serviceName,value:it.serviceId}});
                    })
                    this.onename = res.data.firstSubjectId;
                    this.towname = res.data.parentId;
                }
                this.showDialog=true;
            })
        },
        //删除
        delItem(type,val){
            this.$confirm('此操作将永久删除该服务, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                serviceDelState({serviceId:val.serviceId,state:0}).then(res=>{
                    if(res.code==200){
                        this.$message.success('操作成功！')
                        this.getdata();
                    }
                })
            }).catch(() => {});
            
        },
        //关闭弹窗
        setShowDialog(){
            this.showDialog=false;
        },
        //点击确定
        serve(){
            if(this.type ==2){
                if(!this.showitemr&&!this.showrepea){
                    return this.$message.warning("请选择一项服务功能")
                }
                if(this.showitemr&&this.addItemr.length==0){
                    return this.$message.warning("请添加完成时间的选项")
                }
                if(this.showrepea&&this.addRepeat.length==0){
                    return this.$message.warning("请添加查重率的选项")
                }
            }
            var obj = {
                    //一级分类 为 0   二级分类 给一级分类
                    parentId:0,//分类父级id
                    serviceName:this.form.serviceName,//服务名称
                    serviceDesc:this.form.serviceDesc,//服务描述
                    serviceType:this.type,//当前服务级别
                }
            if(this.dialogTitle == '编辑服务'){
                if(this.type==1){
                    obj.path = (this.imageUrl.indexOf('://')>-1?this.imageUrl.split('://')[1].split('//')[1]:this.imageUrl) || "";
                }else if(this.type==2){
                    obj.parentId = this.onename || 0;
                    let jsonobj ={
                        finishTime:{flag:this.showitemr,list:this.showitemr?JSON.stringify(this.addItemr):[],checkValue:'',placeholder:'请选择工作量'},
                        repeatNum:{flag:this.showrepea,list:this.showrepea?JSON.stringify(this.addRepeat):[],checkValue:'',placeholder:'请选择查重率'},
                    }
                    obj.serviceInfo = JSON.stringify(jsonobj);
                }
                obj.serviceId = this.form.serviceId;
                serviceUpdateState(obj).then(res=>{
                    if(res.code==200){
                        this.getdata();
                        this.showDialog=false;
                    }
                })
            }else{
                if(this.type==1){
                    obj.path = this.imageUrl || "";
                }else if(this.type==2){
                    obj.parentId = this.onename || 0;
                    let jsonobj ={
                        finishTime:{flag:this.showitemr,list:this.showitemr?JSON.stringify(this.addItemr):[],checkValue:'',placeholder:'请选择工作量'},
                        repeatNum:{flag:this.showrepea,list:this.showrepea?JSON.stringify(this.addRepeat):[],checkValue:'',placeholder:'请选择查重率'},
                    }
                    obj.serviceInfo = JSON.stringify(jsonobj);
                }
                console.log(obj)
                addService(obj).then(res=>{
                    console.log(res)
                    if(res.code==200){
                        this.getdata();
                        this.showDialog=false;
                    }
                })
            }
        },

        // 上传前校检格式和大小
        handleBeforeUpload(file) {
            // 校检文件大小
            if (this.fileSize) {
                const isLt = file.size / 1024 / 1024 < this.fileSize;
                if (!isLt) {
                this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
                return false;
                }
            }
            if(this.imageUrl.length>=2){
                this.$message({message:'只能上传两张图片',type:'warning'})
                return false;
            }
            return true;
        },
        handleUploadSuccess(res, file) {
            // 如果上传成功
            if (res.code == 200) {
                // 获取光标所在位置
                console.log(res)
                this.fileList=[res];
                this.imageUrl=res.fileName;
            } else {
                this.$message.error(res.msg);
            }
        },
        //删除文件
        removeItem(file,fileList,index){
            console.log(file)
            console.log(fileList)
            console.log(index)
            if(file.attachmentId!=""&&file.attachmentId!=null){
                deleteAttachment({attachmentId:file.attachmentId}).then(res=>{
                    if(res.code==200){
                        this.fileList.splice(this.fileList.findIndex((profile) => profile.attachmentId === file.attachmentId),1)
                        this.form.attachmentVOList.splice(this.fileList.findIndex((profile) => profile.attachmentId === file.attachmentId),1)
                    }
                })
                return true
            }else{
                return true
            }
        },
        handleUploadError() {
            this.$message.error("上传失败");
        },
     
    
        //远程搜索一级分类
        remoteMethod(val){
            if(val!==""){
               this.getarr(1).then(res=>{
                this.oneArr = res.rows.map(it=>{return {label:it.serviceName,value:it.serviceId}});
               });
            }else{
                this.oneArr = [];
            }
        },
        //远程搜索二级分类
        remoteMethodtow(val){
            if(val!==""){
                this.getarr(2).then(res=>{
                    this.towArr = res.rows.map(it=>{return {label:it.serviceName,value:it.serviceId}});
                });
            }else{
                this.towArr = [];
            }
        },

        async getarr(val){
            var formData = new FormData();
            formData.append('serviceType',val)
            let res = await selectServices({formData});
            if(res.code==200){
                console.log(res.rows)
                return res;
            }else{
                return [];
            }
        },
    }
}
</script>
<style lang='scss' scoped>
.diction{
    width: 100%;
    height: 100%;
    padding: 20px;
    
    .avatar-uploader-icon {
        border: 1px dashed #d9d9d9;
        font-size: 28px;
        color: #8c939d;
        width: 68px;
        height: 68px;
        line-height: 68px;
        border-radius: 6px;
        text-align: center;
    }
    .avatar-uploader-icon:hover{
        border-color: #409EFF;
    }
    .avatar {
        width: 68px;
        height: 68px;
        display: block;
    }
}
.form_item{
    width: 100%;
    .form_item_select{
        display: inline-block;
        vertical-align: middle;
    }
    span{
        display: inline-block;
        vertical-align: middle;
        margin-right:10px;
    }
    .form_item_switch{
        display: inline-block;
        vertical-align: middle;
        margin-right: 10px;
    }
    .form_item_btn{
        display: inline-block;
        vertical-align: middle;
        margin-left: 20px;
    }
}
</style>